
package com.x52im.rbchat.logic.chat_root.sendlocation;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.eva.android.widget.DataLoadableActivity;
import com.eva.framework.dto.DataFromServer;
import com.google.gson.Gson;
import com.x52im.rbchat.R;
import com.x52im.rbchat.logic.chat_root.sendlocation.impl.SearchLocationListAdapter;
import com.x52im.rbchat.logic.chat_root.sendlocation.utils.LocationOnItemClickLisenter;
import com.x52im.rbchat.logic.chat_root.sendlocation.utils.LocationSPUtils;
import com.x52im.rbchat.logic.chat_root.sendlocation.utils.LocationUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 搜索位置的实现类。
 *
 * 有关高德地图的开发者手册，请见：https://lbs.amap.com/api/android-sdk/summary
 * 本类的原始代码来自开源工程：https://github.com/xiaofuchen/WeixinLocation
 *
 * @author 原作者：xiaofuchen, 优化和修订：JackJiang
 * @since 6.0
 */
public class SearchLocationActivity extends DataLoadableActivity {

    private final String TAG = SearchLocationActivity.class.getSimpleName();

    private Button mIvBack;
    private EditText mEtSearch;
    private RecyclerView mRecyclerView;
    private List<PoiItem> mList;
    private SearchLocationListAdapter mSearchAddressAdapter;

    private ImageView mProgressView;
    private Animation mProgressViewAnimation;
    private View mLayoutOfNoData;
    private TextView mHintViewOfNoData;

    private PoiSearch mPoiSearch;
    private PoiSearch.Query mQuery;
    private PoiSearch.OnPoiSearchListener mOnPoiSearchListener;

    private Gson gson;
    public AMapLocation location;

    @Override
    protected void onResume() {
        super.onResume();
        if (null == location) {
            // 获取保存的定位信息
            String s = LocationSPUtils.getString(this, LocationUtils.LOCATION_INFO);
            if (!TextUtils.isEmpty(s)) {
                try {
                    location = gson.fromJson(s, AMapLocation.class);
                } catch (Exception ex) {
                    Log.w(TAG, ex);
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPoiSearch) {
            mPoiSearch = null;
        }
    }

    @Override
    protected DataFromServer queryData(String... params) {
        return null;
    }

    @Override
    protected void refreshToView(Object dateToView) {
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.chatting_get_location_search_activity);

        mIvBack = findViewById(R.id.chatting_location_search_activity_iv_back);
        mEtSearch = findViewById(R.id.chatting_location_search_activity_et_search);

        mRecyclerView = findViewById(R.id.chatting_location_search_activity_recyclerview);

        mProgressViewAnimation = AnimationUtils.loadAnimation(this, R.anim.widget_loading_big1);
        mProgressView = findViewById(R.id.chatting_location_search_activity_progress_view);
        mLayoutOfNoData = findViewById(R.id.chatting_location_search_activity_nodata_LL);
        mHintViewOfNoData = findViewById(R.id.chatting_location_search_activity_nodata_hintView);


        mList = new ArrayList<>();
        mSearchAddressAdapter = new SearchLocationListAdapter(this, mList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mSearchAddressAdapter);

        gson = new Gson();

        // 获取焦点并自动弹出输入法
        try{
            mEtSearch.requestFocus();
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
        catch(Exception e){
            Log.w(TAG, e);
        }
    }

    @Override
    protected void initListeners() {
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.chatting_location_search_activity_iv_back:
                        finish();
                        break;
                }
            }
        });

        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (null != editable) {

                    // 没有输入则清空搜索记录
                    if (0 == editable.length()) {
                        mList.clear();
                        mSearchAddressAdapter.setList(mList, "");
                    } else {
                        if (null != location) {
                            doGetAddressListBySearchQuery(editable.toString(), location.getCity(), new LatLonPoint(location.getLatitude(), location.getLongitude()));
                        } else {
                            doGetAddressListBySearchQuery(editable.toString(), "", null);
                        }
                    }
                }
            }
        });

        mSearchAddressAdapter.setOnItemClickLisenter(new LocationOnItemClickLisenter() {
            @Override
            public void onItemClick(int position) {
                PoiItem poiItem = mList.get(position);

                // 获取信息并回传上一页面
                if (null != poiItem) {
                    Intent intent = new Intent();
                    intent.putExtra(LocationUtils.SEARCH_INFO, poiItem);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });

        mOnPoiSearchListener = new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult result, int i) {
                if (i == 1000) {
                    // 搜索poi的结果
                    if (result != null && result.getQuery() != null) {

                        if (result.getQuery().equals(mQuery)) {

                            showContent(ContentType.data);

                            // 是否是同一条
                            if (null != mList) {
                                mList.clear();
                            }

                            if(result.getPois().size() > 0) {
                                // 取得第一页的poiitem数据，页数从数字0开始
                                mList.addAll(result.getPois());

                                if (null != mSearchAddressAdapter) {
                                    mSearchAddressAdapter.setList(mList, mEtSearch.getText().toString().trim());
                                    mRecyclerView.smoothScrollToPosition(0);
                                }
                            }
                            else
                                showHintContent("没有找到您想要的位置");
                        }
                    }
                    else
                        showHintContent("没有返回正确的结果");
                }
                else
                {
                    showHintContent(LocationUtils.getSearchResponseErrorCodeDesc(i));
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {
            }
        };
    }

    /**
     * 开始进行poi搜索
     */
    protected void doGetAddressListBySearchQuery(String keyWord, String city, LatLonPoint lpTemp) {
        //第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        mQuery = new PoiSearch.Query(keyWord, "", city);
        // 设置每页最多返回多少条poiitem
        mQuery.setPageSize(20);
        // 设置查第一页
        mQuery.setPageNum(0);

        mPoiSearch = new PoiSearch(this, mQuery);
        mPoiSearch.setOnPoiSearchListener(mOnPoiSearchListener);
        if (lpTemp != null) {
            // 该范围的中心点-----半径，单位：米-----是否按照距离排序
            mPoiSearch.setBound(new PoiSearch.SearchBound(lpTemp, 10000, true));
        }
        // 异步搜索
        mPoiSearch.searchPOIAsyn();

        // 显示加载进度
        this.showContent(ContentType.progress);
    }

    public void showHintContent(String hint)
    {
        this.setNoDataHint(hint);
        this.showContent(ContentType.noData);
    }

    public void showContent(ContentType ct) {
        switch (ct) {
            case data: {
                this.mRecyclerView.setVisibility(View.VISIBLE);
                this.mProgressView.setVisibility(View.GONE);
                this.mProgressView.clearAnimation();
                this.mLayoutOfNoData.setVisibility(View.GONE);
                break;
            }
            case noData: {
                this.mRecyclerView.setVisibility(View.GONE);
                this.mProgressView.setVisibility(View.GONE);
                this.mProgressView.clearAnimation();
                this.mLayoutOfNoData.setVisibility(View.VISIBLE);
                break;
            }
            case progress: {
                this.mRecyclerView.setVisibility(View.GONE);
                this.mProgressView.setVisibility(View.VISIBLE);
                this.mProgressView.startAnimation(mProgressViewAnimation);
                this.mLayoutOfNoData.setVisibility(View.GONE);
                break;
            }
        }
    }

    public void setNoDataHint(String hint) {
        this.mHintViewOfNoData.setText(hint);
    }

    private enum ContentType{
        data,
        noData,
        progress
    }
}
